package com.andkrup.web.navigation {
	import com.andkrup.events.NavigateEvent;
	import com.andkrup.web.navigation.INavigationManager;
	import com.andkrup.web.navigation.Navigator;
	import com.andkrup.web.navigation.NavigatorItem;

	/**
	 * @author ak
	 * 
	 * A Menu class that works without being in the display-tree
	 */
	public class BasicNavigator implements Navigator {
		private var items:Array;
		private var navManager:INavigationManager;

		public function get commandpilot():INavigationManager{
			return navManager;
		}
		public function set commandpilot(value:INavigationManager):void{
			if(navManager){
				navManager.unregisterNavigator(this);
			}
			navManager = value;
			navManager.registerNavigator(this);
		}

		public function BasicNavigator(pilot:INavigationManager = null){
			items = [];
			commandpilot = pilot;
		}
		
		public function hasNavigatorItem(item:NavigatorItem):Boolean {
			for each(var navitem:NavigatorItem in items){
				if(item==navitem){
					return true;
				}
			}
			return false;
		}
		
		public function addNavigatorItem(item:NavigatorItem):void {
			if(!hasNavigatorItem(item)){
				items.push(item);
				item.addEventListener(NavigateEvent.NAVIGATE, onNavigationStateChange, false, 0, true);
			}
		}
		
		public function removeNavigatorItem(item:NavigatorItem):void {
			var l:uint = items.length;;
			for(var i:uint = 0; i < l; i++){
				if(item==items[i]){
					items.splice(i, 1);
					item.removeEventListener(NavigateEvent.NAVIGATE, onNavigationStateChange);
					break;
				}
			}
		}
		
		public function getNavigatorItemByKey(key:String):NavigatorItem{
			for each(var navitem:NavigatorItem in items){
				if(key==navitem.command.name){
					return navitem;
				}
			}
			return null;
		}
		
		public function onNavigationStateChange(ne:NavigateEvent):void {
			commandpilot.handleNavigation(ne.command);
		}
	}
}
